import React, { useEffect, useState } from 'react';
import { ListView as ListViewModel } from '../core/ListView';
import { ViewController } from '../core/ViewController';
import { Action } from '../core/Action';
import { DataGrid } from 'devextreme-react/data-grid';
import './ListView.less';

interface ListViewProps {
  model: ListViewModel;
}

/**
 * ListView Component - React component for the ListView core class
 */
const ListView: React.FC<ListViewProps> = ({ model }) => {
  const [loading, setLoading] = useState<boolean>(true);
  const [data, setData] = useState<any[]>([]);
  const [error, setError] = useState<string | null>(null);
  
  // Load data when component mounts
  useEffect(() => {
    console.log('ListView component: model =', model);
    
    // Debug controllers and actions
    if (model.controllers && model.controllers.length > 0) {
      console.log('ListView component: Controllers found:', model.controllers.length);
      model.controllers.forEach((controller: ViewController) => {
        console.log(`Controller: ${controller.id}, Actions:`, controller.actions);
      });
    } else {
      console.warn('ListView component: No controllers available');
    }
    
    const loadData = async () => {
      try {
        if (model.dataSource) {
          console.log('ListView component: Loading data from data source');
          setLoading(true);
          
          // Load data
          await model.dataSource.load();
          
          // Get data from data source
          const loadedData = model.dataSource.data;
          console.log('ListView component: Data loaded successfully', loadedData);
          setData(loadedData || []);
          
          // Auto-select the first item if data exists and no item is currently selected
          if (loadedData && loadedData.length > 0 && !model.selectedItem) {
            console.log('ListView component: Auto-selecting first item', loadedData[0]);
            model.selectedItem = loadedData[0];
          }
        } else {
          console.warn('ListView component: No data source available');
          setData([]);
        }
      } catch (err) {
        console.error('ListView component: Error loading data', err);
        setError('Failed to load data. Please try again later.');
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
  }, [model]);

  // Get the view configuration from the model
  const viewConfig = model.render();
  console.log('ListView component: viewConfig =', viewConfig);
  
  // Set up data grid options based on the model
  const columns = viewConfig.columns.map((column: any) => ({
    dataField: column.fieldName,
    caption: column.caption,
    width: column.width,
    visible: column.visible !== false,
    dataType: column.dataType || 'string',
    format: column.format,
    alignment: column.alignment || 'left'
  }));

  if (error) {
    return (
      <div className="mini-xaf-list-view-component error">
        <h2>{viewConfig.caption}</h2>
        <div className="error-message">
          <p>{error}</p>
          <button onClick={() => window.location.reload()}>Retry</button>
        </div>
      </div>
    );
  }

  return (
    <div className="mini-xaf-list-view-component">
      <div className="list-view-header">
        <h2>{viewConfig.caption}</h2>
        <div className="action-buttons">
          {/* Render actions from view controllers */}
          {model.controllers && model.controllers.length > 0 ? (
            model.controllers.flatMap((controller: ViewController) => 
              controller.actions.filter((action: Action) => action.visible)
                .map((action: Action, index: number) => (
                  <button 
                    key={`${controller.id}-${action.id}-${index}`}
                    onClick={() => action.execute()}
                    disabled={!action.enabled}
                    className="action-button"
                  >
                    {action.imageUrl && (
                      <img src={action.imageUrl} alt="" className="action-icon" />
                    )}
                    {action.caption}
                  </button>
                ))
            )
          ) : (
            <div>No actions available</div>
          )}
        </div>
      </div>

      <DataGrid
        dataSource={data}
        columns={columns}
        showBorders={true}
        hoverStateEnabled={true}
        selection={{ mode: 'single' }}
        paging={{ pageSize: 20 }}
        filterRow={{ visible: true }}
        headerFilter={{ visible: true }}
        searchPanel={{ visible: true, width: 240 }}
        loadPanel={{ enabled: loading }}
        onSelectionChanged={e => {
          model.selectedItem = e.selectedRowsData && e.selectedRowsData.length > 0 ? e.selectedRowsData[0] : null;
        }}
      />
    </div>
  );
};

export default ListView;
